package com.github.pig.admin.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>Author: lxm
 */
public abstract class AbstractServer  implements ServerInterface,Runnable {

    private static Logger logger = LoggerFactory.getLogger(AbstractServer.class);

    //pool
    protected volatile ExecutorService pool;
    //线程状态
    protected volatile boolean run;
    //间隔时间
    protected volatile int time;
    //线程池大小
    protected volatile int poolSize;

    protected volatile int dataSize;

    public void init(){
        time = 2000;
        poolSize = 20;
        dataSize = 20;
        turnOn();

    }


    @Override
    public boolean turnOn() {
        synchronized (this){
            if(isTerminated()){
                run = true;
                if(poolSize>0){
                    pool = Executors.newFixedThreadPool(poolSize+1);
                }else {
                    pool = Executors.newSingleThreadExecutor();
                }
                logger.info(this+" turnOn!");
                pool.execute(this);
                return true;
            }
            return false;
        }

    }

    @Override
    public void turnOff() {
        synchronized (this){
            run = false;
            logger.info(this+" turnOff!");
        }
    }

    @Override
    public boolean isShutdown() {
        return !run;
    }

    @Override
    public boolean isTerminated() {
        return (pool==null || (pool!=null&&pool.isTerminated()));
    }


    public int getTime() {
        return time;
    }

    public void setTime(int time) {
        this.time = time;
    }

    public int getPoolSize() {
        return poolSize;
    }

    public void setPoolSize(int poolSize) {
        this.poolSize = poolSize;
    }

    public int getDataSize() {
        return dataSize;
    }

    public void setDataSize(int dataSize) {
        this.dataSize = dataSize;
    }
}
